//
//  UserMessageViewController.m
//  BGM
//
//  Created by liuqin on 2018/11/27.
//  Copyright © 2018年 com.alirtc.demo. All rights reserved.
//

#import "UserMessageViewController.h"

#import "Common.h"

#import "UserPageView.h"
#import "UserPageDetailView.h"
#import "AFHTTPSessionManager.h"
#import "BGMHTTP.h"

#import "CommonView.h"
#import "BGMUser.h"
#import "BGMCity.h"
#import "QiniuSDK.h"
#import "BGMDateView.h"
#import "GCQiniuUploadManager.h"
#import "BGMNewImage.h"

#import "SVProgressHUD.h"

#import "MeChangeInfoView.h"
#import "GFAddressPicker.h"

#import "LoginUserJobView.h"


@interface UserMessageViewController ()<UserPageViewDeleage,UserPageDetailViewDeleage,BGMDateViewDelegate,UINavigationControllerDelegate,
UIImagePickerControllerDelegate,MeChangeInfoViewDelegate,GFAddressPickerDelegate,
LoginUserJobViewDelegate>

@property (nonatomic,strong)MeChangeInfoView *changBgView;

@property (nonatomic, strong)UIScrollView *bgSC;;

@property (nonatomic, strong)NSString  *sex;
@property (nonatomic, strong)NSString  *birth;

@property (nonatomic, strong)UserPageView *pageView1;
@property (nonatomic, strong)UserPageDetailView *pageView2;
@property (nonatomic, strong)BGMDateView *dataView;
@property (nonatomic, strong)UIImage *userImage; //用户头像
@property (nonatomic, strong)NSString *userURL; //用户头像

@property (nonatomic, strong)NSArray *userTitles;
@property (nonatomic, strong)NSArray *userIntrys;
@property (nonatomic, strong)NSMutableArray *userChangeTitles;
@property (nonatomic, strong)NSMutableString *resultUserTitles;

@property (nonatomic, strong)GFAddressPicker *pickerView;
@property (nonatomic, strong)NSString *userCity;

@property (nonatomic, strong)LoginUserJobView *jobView;
@property (nonatomic, strong)NSString *userJob;


@end

@implementation UserMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    
    self.userCity = @"";

    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    self.userIntrys = [userDefault objectForKey:@"userInstrys"];
    self.userTitles = [userDefault objectForKey:@"usertitle"];
    self.resultUserTitles = [[NSMutableString alloc]init];
    self.userChangeTitles = [[NSMutableArray alloc]init];
    for (int i = 0; i<self.userTitles.count; i++) {
        [self.userChangeTitles addObject:@"0"];
    }
    

    self.sex = @"";
    self.birth = @"";
    UIImageView *navview  = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, 70)];
    [navview setImage:[UIImage imageNamed:@"navImage"]];
    [self.view addSubview:navview];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, 20, SCREENW, 50)];
    titleLabel.textColor = bgmmainColor;
    titleLabel.font = [UIFont systemFontOfSize:20];
    titleLabel.text = @"填写基本信息";
    [navview addSubview:titleLabel];
    
    self.bgSC = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH)];
    [self.view addSubview:self.bgSC];
    [self.view insertSubview:self.bgSC belowSubview:navview];
    self.bgSC.contentSize = CGSizeMake(SCREENW, SCREENH*2);
    self.bgSC.showsHorizontalScrollIndicator = NO;
    self.bgSC.showsVerticalScrollIndicator = NO;
    self.bgSC.pagingEnabled = YES;
    self.pageView1 = [[UserPageView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH)];
    self.pageView1.deleagte = self;
    [self.bgSC addSubview:self.pageView1];
    
    self.pageView2 = [[UserPageDetailView alloc]initWithFrame:CGRectMake(0, SCREENH, SCREENW, SCREENH)];
    self.pageView2.deleagte = self;
    [self.bgSC addSubview:self.pageView2];
    
    self.dataView = [[BGMDateView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH)];
    self.dataView.userDateDelegate = self;
    [self.view addSubview:self.dataView];
    self.dataView.hidden = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenBirthView)];
    [self.view addGestureRecognizer:tap];
    
    
    self.changBgView = [[MeChangeInfoView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH)];
    self.changBgView.delegate = self;
    [self.view addSubview:self.changBgView];
    [self.view bringSubviewToFront:self.changBgView];
    self.changBgView.hidden = YES;
    
    self.pickerView = [[GFAddressPicker alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    self.pickerView.delegate = self;
    self.pickerView.font = [UIFont boldSystemFontOfSize:18];
    [self.view addSubview:self.pickerView];
    self.pickerView.hidden = YES;
    
    self.jobView = [[LoginUserJobView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH)];
    self.jobView.jobDelegate = self;
    self.jobView.titleContents = [userDefault objectForKey:@"userInstrys"];
    [self.jobView.userTable reloadData];
    self.jobView.hidden = YES;
    
    UIApplication *app = [UIApplication sharedApplication];
    [app.keyWindow addSubview:self.jobView];
    
}

- (void)hiddenBirthView{
    self.dataView.hidden = YES;
}
#pragma mark DELEAGTE
-(void)seleHeadImage{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消 " style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * action) {
                                                             //响应事件
                                                             NSLog(@"action = %@", action);
                                                         }];
    UIAlertAction* deleteAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action) {
 ;
                                                             [self seleHeadImage:1];
                                                         }];
    UIAlertAction* saveAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action) {
 
                                                           [self seleHeadImage:2];
                                                       }];
    [alert addAction:saveAction];
    [alert addAction:cancelAction];
    [alert addAction:deleteAction];
    [self presentViewController:alert animated:YES completion:nil];
    
}
#pragma mark 修改个人头像
//1拍 2 选
- (void)seleHeadImage:(int)i {
    
    // 判断系统是否支持相机
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self; //设置代理
    imagePickerController.allowsEditing = YES;
    if (i == 1) {
        //拍照
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }else {
        //相册
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
    
    
}
// 获取图片后操作
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:(NSString *) kUTTypeImage] && picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImage *edit = [info objectForKey:UIImagePickerControllerEditedImage];
        self.userImage = edit;
        [self.pageView1.headImage setImage:self.userImage forState:UIControlStateNormal];
        
    }else if ([mediaType isEqualToString:(NSString *) kUTTypeImage] && picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary){
        UIImage *edit = [info objectForKey:UIImagePickerControllerEditedImage];
        self.userImage = edit;
        [self.pageView1.headImage setImage:self.userImage forState:UIControlStateNormal];
 
    }
//    [self upImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)clickBrithView{
    self.dataView.hidden = NO;
}

- (void)seleSex:(int)tag{
    switch (tag) {
        case 99:   //男
        {
            self.sex = @"1";
        }
            break;
        case 100: //女
        {
            self.sex = @"2";
        }
            break;
            
        default:
            break;
    }

}
#pragma mark 选择城市
- (void)clickCity{
    self.pickerView.hidden = NO;
}
#pragma mark 选择个人标签
- (void)getTitle{
    self.changBgView.hidden = NO;
    self.changBgView.nameView.hidden = YES;
    self.changBgView.sexView.hidden = YES;
    self.changBgView.TitleView.hidden = NO;
    self.changBgView.userTitle.text = @"个性标签";
    self.changBgView.isTitle = NO;
    self.changBgView.dateView.hidden = YES;
    self.changBgView.titleContents = self.userTitles;
    self.changBgView.userSeleArray = self.userChangeTitles;
    [self.changBgView.userTable reloadData];
}
- (void)changeUserLabel:(NSMutableArray *)array{
    self.changBgView.hidden = YES;
    [self.resultUserTitles deleteCharactersInRange:NSMakeRange(0, self.resultUserTitles.length)];
    
    for (int i = 0; i<array.count; i++) {
        NSString *str = [array objectAtIndex:i];
        if ([str isEqualToString:@"1"]) {
            NSDictionary *dic = [self.userTitles objectAtIndex:i];
            [self.resultUserTitles appendString:[NSString stringWithFormat:@"%@,",[dic objectForKey:@"lableName"]]];
        }
    }
    
    if (self.resultUserTitles.length>0) {
        [self.resultUserTitles deleteCharactersInRange:NSMakeRange(self.resultUserTitles.length-1, 1)];
        BGMTextView *titleView  = [self.pageView2 viewWithTag:203];
        titleView.myText.font = [UIFont systemFontOfSize:13];
        titleView.myText.text = [NSString stringWithFormat:@"个性标签:%@",self.resultUserTitles];
    }
    
    self.changBgView.hidden = YES;
    
}
-(void)hideUserLabel{
    self.changBgView.hidden = YES;
}



#pragma mark 选择个人工作
- (void)getJob{
    self.jobView.hidden = NO;
}
- (void)changeJob:(NSString *)job{
    self.userJob = job;
    BGMTextView *jobView  = [self.pageView2 viewWithTag:201];
    jobView.myText.font = [UIFont systemFontOfSize:13];
    jobView.myText.text = [NSString stringWithFormat:@"行业:%@",job];
    self.jobView.hidden = YES;

}
- (void)hiddenJobview{
    self.jobView.hidden = YES;
}



    

 
- (void)gotoNextVC{
    [self upHeadImage];
}
- (void)upHeadImage{
    
    BGMNewImage *newImage = [[BGMNewImage alloc]init];
    NSData *data = [newImage resetSizeOfImageData:self.userImage maxSize:1024];
    
    NSString *token =  [[GCQiniuUploadManager sharedInstance] createToken];
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    QNUploadOption *up = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    NSString *name = [NSString stringWithFormat:@"%@_ioshead.png",timeString];
    
    [upManager putData:data key:name token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        NSString *url = [NSString stringWithFormat:@"http://yaobangma.com/%@",[resp objectForKey:@"key"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.userURL = url;
            [self clickGoBtn];
        });
    } option:up];
    
    
}
#pragma mark --注册---
- (void)clickGoBtn{
  
    NSString *name = self.pageView1.iphoneView.myText.text;
    NSString *nameStr=[name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    if (nameStr.length==0) {
        [SVProgressHUD showInfoWithStatus:@"姓名必填！"];
        return;
    }else if (self.birth.length == 0){
        [SVProgressHUD showInfoWithStatus:@"生日必填！"];
        return;
    }else if (self.userImage == nil){
        [SVProgressHUD showInfoWithStatus:@"头像必填！"];
        return;
    }else if (self.sex.length==0){
        [SVProgressHUD showInfoWithStatus:@"性别必填！"];
        return;
    }
   
    NSDictionary *parameters = @{@"phoneNumber":self.iphone,@"name":self.pageView1.iphoneView.myText.text,@"gender":self.sex,@"birthday":self.birth,@"city":self.userCity.length>0?self.userCity:@"中国",@"industry":self.userJob.length>0?self.userJob:@"",@"personalLabel":self.resultUserTitles.length>0?self.resultUserTitles:@"",@"headImage":self.userURL};
    
    [BGMHTTP requestWithMethodName:@"login/register" parameters:parameters completion:^(BOOL success, NSError *error, NSDictionary *result) {
        NSDictionary *dic = result;
        [self gotoMainVC:dic];

    }];

}

- (void)saveBirth:(NSString *)brith{
    self.birth = brith;
    self.pageView1.cordView.myText.text = brith;
    [self hiddenBirthView];
}

- (void)gotoMainVC:(NSDictionary *)dic{
 
    NSString *code = [NSString stringWithFormat:@"%@",[dic objectForKey:@"code"]];
    if ([code isEqualToString:@"200"]) {  //注册成功
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSDictionary *userDic = [dic objectForKey:@"data"];
            BGMUser *user = [BGMUser shareInstance];
            user.birthday = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"birthday"]];
            user.city = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"city"]];
            user.gender = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"gender"]];
            user.headImage = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"headImage"]];
            user.imageArray = [userDic objectForKey:@"image"];
            user.industry = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"industry"]];
            user.name = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"name"]];
            user.personalLabelArray = [userDic objectForKey:@"personalLabel"];
            user.phone = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"phone"]];
            user.spectralValue = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"spectralValue"]];
            user.userId = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"usersId"]];
            user.userToken = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"token"]];
            user.imToken = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"imToken"]];
            
            NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
            [ud setObject:@"1" forKey:ISLOGINKEY];//登录成功
            [ud setObject:userDic forKey:usermessage];//登录成功
            [ud synchronize];
            
            
            user.userId = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"usersId"]];
            user.userToken = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"token"]];
            user.imToken = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"imToken"]];
            
            
            [[NSNotificationCenter defaultCenter]postNotificationName:@"gotoMainVC" object:nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"LoginSuccess" object:nil];
        });
    }else{
//        UIAlertController *alert = [CommonView getCommonAlert:@"提示code为" message:[NSString stringWithFormat:@"code = %@",code] ok:@"确定" cancel:@"取消"];
//        [self presentViewController:alert animated:YES completion:nil];
    }
}
/** 代理方法返回省市区*/
- (void)GFAddressPickerWithProvince:(NSString *)province
                               city:(NSString *)city area:(NSString *)area{
    self.userCity = city;
    BGMTextView *jobView  = [self.pageView2 viewWithTag:301];
    jobView.myText.font = [UIFont systemFontOfSize:13];
    jobView.myText.text = [NSString stringWithFormat:@"城市:%@",city];
    self.pickerView.hidden = YES;

}

/** 取消代理方法*/
- (void)GFAddressPickerCancleAction{
    self.pickerView.hidden = YES;
}

@end
